// ==UserScript==
// @name          Twitter URL Resolver
// @namespace     http://almaer.com/firefox/userscripts/
// @description   Replace tinyurl / is.gd / snurl / ... URLs
// @include       http://twitter.com/*
// @exclude       http://twitter.com/account/*
// @exclude       http://twitter.com/logout*
// @exclude       https://twitter.com/invitations
// ==/UserScript==
 
(function() {	
	var jQuery = unsafeWindow['jQuery']; // Bring it over from the dark side
//	var console = unsafeWindow['console'];
	
	// Given the Tweet, replace with the real one
	var resolveURLs = function(el) {		
		var text = jQuery.trim(jQuery(el).html());
		var newtext = text;

    var matches = text.match(/(http:\/\/[A-z0-9.\/,?%+]+)/g);
    if (!matches) return;
    
    var savedURLs = {};
    for (var x = 0; x < matches.length; x++) {
      var url = matches[x];
      
      if (savedURLs[url]) {
        continue;
      } else {
        savedURLs[url] = true;
      }
      
      Endpoint.resolve(url, function(resulturl, originalurl) {
        if (!Endpoint.isRedirecting(resulturl, originalurl)) return;
        
	newtext = newtext.replace("href=\""+originalurl, "href=\""+resulturl+"\" title=\""+resulturl, "g");
	newtext = newtext.replace(originalurl, resulturl.length > 30 ? resulturl.substr(0,30)+"..." : resulturl, "g");
        jQuery(el).html(newtext);
      });
    }    
	}

	// Go through the twitters
	window.addEventListener('load', function(event) {
		if (!unsafeWindow['jQuery']) return; // If jQuery hasn't been loaded we are in trouble
				
		jQuery('.entry-content').each(function() {
			resolveURLs(this);
		});
		
	}, false);
	
	// -- Load in the Endpoint code (and s/window/unsafeWindow/)
  var Endpoint = new function() {
    var RESOLVER_URL = 'http://almaer.com/endpoint/resolver.php';
    var RESOLVER_CALLBACK = '__Endpoint_resolve';

    var count = 0;

    // touch my privates
    var append = function(url) {
      var appender = document.createElement('script');
      appender.src = url;
      appender.type = 'text/javascript';
      document.getElementsByTagName('body')[0].appendChild(appender);
    }

    // feeling public
    return {
      resolve: function(url, userCallback) {
        var serverCallback = RESOLVER_CALLBACK + (count++);
        var serverUrl = RESOLVER_URL 
                      + '?url=' + url
                      + '&callback=' + serverCallback;

        // Global link to run the callback
        unsafeWindow[serverCallback] = userCallback;

        append(serverUrl); // Hit the server proxy via script append
      },

      isRedirecting: function(newurl, originalurl) {
        return (newurl != '') && (newurl != originalurl);
      }
    };
  };
  // -- End the Endpoint code
})();
